package chapter1;

import java.util.Iterator;

public class ArrayBag<T> implements Bag<T> {
    private int index = 0;
    private T[] arr = (T[]) new Object[16];

    public ArrayBag() {

    }

    public ArrayBag(int size) {
        arr = (T[]) new Object[size];
    }

    @Override
    public void add(T item) {
        if (item == null) {
            throw new NullPointerException("item can not be null");
        }
        if (index >= arr.length) {
            resize(arr.length * 2);
        }
        arr[index++] = item;
    }

    private void resize(int size) {
        T[] temp = (T[]) new Object[size];
        for (int i = 0; i < index; i++) {
            temp[i] = arr[i];
        }
        arr = temp;
    }

    @Override
    public boolean isEmpty() {
        return index == 0;
    }

    @Override
    public int size() {
        return arr.length;
    }

    @Override
    public Iterator<T> iterator() {
        return new ArrayIterator();
    }

    private class ArrayIterator implements Iterator<T> {
        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            return currentIndex < index;
        }

        @Override
        public T next() {
            return arr[currentIndex++];
        }
    }
}
